package com.example.CarManagement.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.CarManagement.common.Result;
import com.example.CarManagement.enumPojo.ApplicationStatus;
import com.example.CarManagement.enumPojo.DriverStatus;
import com.example.CarManagement.enumPojo.OrderStatus;
import com.example.CarManagement.sys.dto.OrderDto;
import com.example.CarManagement.sys.entity.*;
import com.example.CarManagement.sys.mapper.*;
import com.example.CarManagement.sys.service.INotificationService;
import com.example.CarManagement.sys.service.IOrdersService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 订单表，记录派车信息和实际用车情况 服务实现类
 * </p>
 *
 * @author 徐佳彪
 * @since 2025-07-23
 */
@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements IOrdersService {


    @Resource
    private UserMapper userMapper;

    @Resource
    private UserServiceImpl userService;


    @Resource
    private CarInfoMapper carInfoMapper;


    @Resource
    private DriversMapper driversMapper;


    @Resource
    private ApplicationsMapper applicationsMapper;


    @Resource
    private OrderImgsMapper orderImgsMapper;

    @Resource
    private INotificationService notificationService;


    @Override
    public Result<?> getPageList(Integer pageNo, Integer pageSize, String applicationId, String orderNumber) {

        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        if (applicationId != null) {
            queryWrapper.like(Orders::getApplicationId, applicationId);
        }
        if (orderNumber != null) {
            queryWrapper.eq(Orders::getOrderNumber, orderNumber);
        }

        // 按创建时间倒序排序（最新在前）
        queryWrapper.orderByDesc(Orders::getCreatedAt);

        Page<Orders> ordersPage = this.baseMapper.selectPage(new Page<>(pageNo, pageSize), queryWrapper);

        Integer total = (int) ordersPage.getTotal();
        List<Orders> applications = ordersPage.getRecords();

        Map<String, Object> data = new HashMap<>();
        data.put("rows", applications);
        data.put("total", total);

        return Result.success(data);
    }

    @Override
    public Result<?> orderInfo(String id) {
        Orders orders = this.baseMapper.selectById(id);

        // 查询用户名称
        String dispatcherId = orders.getDispatcherId();
        User user = userMapper.selectById(dispatcherId);

        // 车辆名称
        CarInfo carInfo = carInfoMapper.selectById(orders.getVehicleId());

        // 司机司机名称
        LambdaQueryWrapper<Drivers> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Drivers::getDriverId, orders.getDriverId());
        Drivers drivers = driversMapper.selectOne(queryWrapper);
        User driverUser = userMapper.selectById(drivers.getUserId());

        Map<String, Object> data = new HashMap<>();

        data.put("order", orders);
        data.put("username", user.getUsername());
        data.put("plateNumber", carInfo.getPlateNumber());
        data.put("driversName", driverUser.getUsername());

        return Result.success(data);
    }

    /**
     * 获取司机任务
     *
     * @param token
     * @param orderStatus
     * @return
     */
    @Override
    public Result<?> dispatchTask(String token, OrderStatus orderStatus) {
        LoginUser userInfo = userService.getUserInfo(token);


        LambdaQueryWrapper<Drivers> driversLambdaQueryWrapper = new LambdaQueryWrapper<>();
        driversLambdaQueryWrapper.eq(Drivers::getUserId, userInfo.getUser().getId());
        Drivers drivers = driversMapper.selectOne(driversLambdaQueryWrapper);

        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Orders::getDriverId, drivers.getDriverId());
        queryWrapper.eq(Orders::getStatus, orderStatus);

        List<Orders> orders = this.baseMapper.selectList(queryWrapper);

        List<Map<String, Object>> dat = new ArrayList<>();
        for (Orders order : orders) {
            Map<String, Object> data = new HashMap<>();

            LambdaQueryWrapper<Applications> applicationsLambdaQueryWrapper = new LambdaQueryWrapper<>();
            applicationsLambdaQueryWrapper.eq(Applications::getApplicationNumber, order.getApplicationId());
            Applications applications = applicationsMapper.selectOne(applicationsLambdaQueryWrapper);

            // 查询车辆
            CarInfo carInfo = carInfoMapper.selectById(order.getVehicleId());
            data.put("id", order.getId());
            data.put("title", order.getOrderNumber());
            data.put("startTime", applications.getStartTime());
            data.put("endTime", applications.getEndTime());
            data.put("status", order.getStatus());
            data.put("passengers", applications.getPassengers());
            data.put("departureLocation", applications.getDepartureLocation());
            data.put("destination", applications.getDestination());
            data.put("plateNumber", carInfo.getPlateNumber());
            dat.add(data);
        }


        // 获取当前司机信息
        return Result.success(dat);
    }

    @Override
    public Result<?> getInfoById(String id, String token) {
        Orders order = null;
        if (id.contains("APP")) {
            // 如果id中包含"APP"，则执行相应逻辑
            // 例如：抛出异常或返回错误信
            LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Orders::getApplicationId, id);
            order = this.baseMapper.selectOne(queryWrapper);
        } else {
            order = this.baseMapper.selectById(id);
        }

        Map<String, Object> data = new HashMap<>();

        LambdaQueryWrapper<Applications> applicationsLambdaQueryWrapper = new LambdaQueryWrapper<>();
        applicationsLambdaQueryWrapper.eq(Applications::getApplicationNumber, order.getApplicationId());
        Applications applications = applicationsMapper.selectOne(applicationsLambdaQueryWrapper);
        LoginUser userInfo = userService.getUserInfo(token);

        // 查询图片列表
        LambdaQueryWrapper<OrderImgs> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(OrderImgs::getOrderId, id);
        List<OrderImgs> orderImgs = orderImgsMapper.selectList(lambdaQueryWrapper);

        List<String> imgList = new ArrayList<>();
        for (OrderImgs orderImg : orderImgs) {
            imgList.add(orderImg.getImgPath());
        }

        // 查询车辆
        CarInfo carInfo = carInfoMapper.selectById(order.getVehicleId());
        data.put("id", order.getId());
        data.put("orderId", order.getOrderNumber());


        // 查询司机信息
        data.put("title", applications.getApplicationNumber());
        data.put("avatar", userInfo.getUser().getAvatar());
        data.put("startTime", applications.getStartTime());
        data.put("endTime", applications.getEndTime());
        data.put("status", order.getStatus());
        data.put("passengers", applications.getPassengers());
        data.put("departureLocation", applications.getDepartureLocation());
        data.put("destination", applications.getDestination());
        data.put("plateNumber", carInfo.getPlateNumber());
        data.put("vehicleType", carInfo.getVehicleType());
        data.put("seats", carInfo.getSeatCount());
        data.put("remarks", applications.getPurpose());
        data.put("imgList", imgList);
        data.put("rating", order.getRating());
        data.put("feedback", order.getFeedback());
        data.put("username", userInfo.getUser().getUsername());

        data.put("actualStartTime", order.getActualStartTime());
        data.put("actualEndTime", order.getActualEndTime());

        data.put("phone", userInfo.getUser().getPhoneNumber());


        return Result.success(data);
    }

    /**
     * 开始任务
     *
     * @param id
     * @return
     */
    @Override
    public Result<?> startTask(String id) {
        Orders orders = this.baseMapper.selectById(id);

        // 状态
        if (orders.getStatus() == OrderStatus.dispatched) {
            orders.setStatus(OrderStatus.in_progress);
            orders.setActualStartTime(LocalDateTime.now());

            // 修改申请状态
            // 完成申请
            LambdaQueryWrapper<Applications> applicationsLambdaQueryWrapper = new LambdaQueryWrapper<>();
            applicationsLambdaQueryWrapper.eq(Applications::getApplicationNumber, orders.getApplicationId());
            Applications applications = applicationsMapper.selectOne(applicationsLambdaQueryWrapper);
            applications.setStatus(ApplicationStatus.completed);


            applicationsMapper.updateById(applications);
            orders.setActualStartTime(LocalDateTime.now());
            this.baseMapper.updateById(orders);

            // 给目标用户发送通知
            notificationService.addSystemNotice(applications.getApplicantId(), applications.getApplicationNumber(), "任务开始");


            return Result.success("任务开始");
        } else {
            return Result.fail("任务已开始");
        }

    }

    /**
     * 完成任务
     *
     * @param orderDto
     * @return
     */
    @Override
    public Result<?> completeTask(OrderDto orderDto) {

        Orders orders = this.baseMapper.selectById(orderDto.getId());
        orders.setActualEndTime(LocalDateTime.now());
        orders.setFuelCost(orderDto.getFuelCost());
        orders.setActualMileage(orderDto.getActualMileage());
        orders.setFeedback(orderDto.getFeedback());
        orders.setOtherCost(orderDto.getOtherCost());

        List<String> imgList = orderDto.getImgList();

        for (String s : imgList) {
            OrderImgs orderImgs = new OrderImgs();
            orderImgs.setImgPath(s);
            orderImgs.setOrderId(orderDto.getId());
            orderImgsMapper.insert(orderImgs);
        }
        // 完成任务
        orders.setStatus(OrderStatus.completed);
        orders.setActualEndTime(LocalDateTime.now());
        this.baseMapper.updateById(orders);

        // 完成申请
        LambdaQueryWrapper<Applications> applicationsLambdaQueryWrapper = new LambdaQueryWrapper<>();
        applicationsLambdaQueryWrapper.eq(Applications::getApplicationNumber, orders.getApplicationId());
        Applications applications = applicationsMapper.selectOne(applicationsLambdaQueryWrapper);
        applications.setStatus(ApplicationStatus.completed);
        applicationsMapper.updateById(applications);


        // 设置司机状态为空闲
        LambdaQueryWrapper<Drivers> driversLambdaQueryWrapper = new LambdaQueryWrapper<>();
        driversLambdaQueryWrapper.eq(Drivers::getDriverId, orders.getDriverId());

        Drivers drivers = driversMapper.selectOne(driversLambdaQueryWrapper);
        if (drivers != null) {
            drivers.setStatus(DriverStatus.available);

            driversMapper.update(drivers, driversLambdaQueryWrapper);
        }

        // 设置车辆状态
        LambdaQueryWrapper<CarInfo> carInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        carInfoLambdaQueryWrapper.eq(CarInfo::getId, orders.getVehicleId());
        CarInfo carInfo = carInfoMapper.selectOne(carInfoLambdaQueryWrapper);
        carInfo.setStatus(0);
        carInfoMapper.updateById(carInfo);

        // 给目标用户发送通知
        notificationService.addSystemNotice(applications.getApplicantId(), applications.getApplicationNumber(), "任务已完成");

        return Result.success("任务完成");
    }
}
